package com.yanfan.ba.modbus.test;

import com.serotonin.modbus4j.BatchRead;
import com.serotonin.modbus4j.BatchResults;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ErrorResponseException;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.locator.BaseLocator;
import com.serotonin.modbus4j.code.DataType;
import com.yanfan.ba.util.Modbus4jUtils;

public class PLCCommunication {
    public static void main(String[] args) throws ModbusInitException {
        // 初始化 Modbus Master
        ModbusMaster master = Modbus4jUtils.getMaster("192.168.23.74", 502);
        try {
            master.init();

            // 尝试批量读取寄存器
            System.out.println("批量读取寄存器：");
            batchReadRegisters(master);

            // 单个读取不同数据类型
            System.out.println("\n逐个读取寄存器，尝试不同数据类型：");
            singleReadRegisters(master);

        } catch (ModbusInitException e) {
            System.out.println("初始化 Modbus Master 出现错误：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 销毁 Master
            master.destroy();
        }
        System.out.println("结束==");
    }

    private static void batchReadRegisters(ModbusMaster master) {
        try {
            BatchRead<Number> batch = new BatchRead<>();
            // 假设数据类型为 16 位无符号整数
            for (int i = 0; i < 10; i++) {
                batch.addLocator(i, BaseLocator.holdingRegister(10, i, DataType.TWO_BYTE_INT_UNSIGNED)); // 确保数据类型一致
            }

            // 执行批量读取
            BatchResults<Number> results = master.send(batch);

            // 输出批量读取的结果
            for (int i = 0; i < 10; i++) {
                Object valueObj = results.getValue(i);
                Number value = (valueObj instanceof Number) ? (Number) valueObj : null; // 强制转换
                if (value != null) {
                    System.out.println("Register " + i + ": " + value.intValue());
                } else {
                    System.out.println("Register " + i + ": Null");
                }
            }
        } catch (ModbusTransportException | ErrorResponseException e) {
            System.out.println("批量读取时出现错误：" + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void singleReadRegisters(ModbusMaster master) {
        for (int i = 0; i < 10; i++) {
            try {
                // 读取 16 位无符号整数
                Number value16Unsigned = Modbus4jUtils.readHoldingRegister(master, 1, i, DataType.TWO_BYTE_INT_UNSIGNED);
                System.out.println("Register " + i + " (TWO_BYTE_INT_UNSIGNED): " + value16Unsigned);

                // 读取 16 位有符号整数
                Number value16Signed = Modbus4jUtils.readHoldingRegister(master, 1, i, DataType.TWO_BYTE_INT_SIGNED);
                System.out.println("Register " + i + " (TWO_BYTE_INT_SIGNED): " + value16Signed);

                // 读取 32 位浮点数
                Number valueFloat = Modbus4jUtils.readHoldingRegister(master, 1, i, DataType.FOUR_BYTE_FLOAT);
                System.out.println("Register " + i + " (FOUR_BYTE_FLOAT): " + valueFloat);

            } catch (ModbusTransportException | ErrorResponseException e) {
                System.out.println("读取寄存器 " + i + " 时出现错误：" + e.getMessage());
                e.printStackTrace();
            }
        }
    }
}
